<template>
    <div class="bg-white p-6">
        <el-dialog v-model="state.messageDialogVisible" width="80%">
            <el-form ref="editFormRef" :model="state.editFormData" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="所属部门" prop="departmentID">
                            <el-select v-model="state.editFormData.departmentID" placeholder="请选择"
                                @change="selectDepartmentID">
                                <el-option v-for="item, index in state.departmentList" :key="index"
                                    :label="item.DepartmentName" :value="item.DepartmentID"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责人账号" prop="userId" label-width="120">
                            <el-select v-model="state.editFormData.userId" placeholder="请选择">
                                <el-option v-for="item, index in state.userList" :key="index" :label="item.UserName"
                                    :value="item.UserID"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="公告标题" prop="message">
                            <el-input v-model="state.editFormData.message"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="公告内容">
                            <MyRditor @EditContent="EditContent"></MyRditor>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <div class="flex justify-between mt-2">
                <el-button type="primary" @click="editMessage">提交</el-button>
                <el-button type="plain" @click="state.messageDialogVisible = false">返回</el-button>
            </div>
        </el-dialog>
        <el-row class="mb-1">
            <div class="w-full flex justify-end">
                <el-autocomplete v-model="state.stateData" @input="inputSearch" :fetch-suggestions="querySearchAsync"
                    placeholder="请输入关键字" @select="handleSelect" class="mr-2">
                    <template #suffix>
                        <el-icon color="#000">
                            <Search />
                        </el-icon>
                    </template>
                </el-autocomplete>
                <el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
                <el-button type="primary" :icon="Message" @click="readAll">一键已读</el-button>
                <el-button type="success" :icon="Edit" @click="state.messageDialogVisible = true">编辑公告</el-button>
            </div>
        </el-row>
        <el-tabs v-model="state.activeTab" @tab-click="handleTabClick">
            <el-tab-pane :label="item.title" v-for="item, index in state.tabTitle" :key="index" :name="item.tabName">
                <el-table :data="state.messageList" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" fixed="left" width="50" align="center" />
                    <el-table-column prop="message" label="内容">
                        <template #default="scope">
                            <span>{{ scope.row.message }}</span>
                            <el-badge class="mark ml-1" value="new" v-if="scope.row.status == 1" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="operation_date" label="操作时间" align="center" />
                    <el-table-column fixed="right" label="操作" align="center" width="180">
                        <template #default="scope">
                            <el-button link type="warning" size="small" @click.prevent="openUpdata(scope.row)">
                                <el-icon>
                                    <ChatDotRound />
                                </el-icon>
                                详情
                            </el-button>
                            <el-button link type="danger" size="small" @click.prevent="deleteRow_w(scope.row)">
                                <el-icon>
                                    <DeleteFilled />
                                </el-icon>
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </el-tab-pane>
        </el-tabs>
        <el-pagination @size-change="handlehSizeChange" @current-change="handlehCurrentChange" :page-sizes="[5, 8, 10]"
            :page-size="state.page.pageSize" layout="total, jumper, prev, pager, next, sizes" :total="state.page.total"
            class="mt-2">
        </el-pagination>
    </div>
</template>

<script setup>
import MyRditor from './MyEditor.vue'
import { formatDate } from '../utils/formatData.js'
import { onMounted, reactive, ref } from 'vue';
import { messageRead, messageUpdate, messageDelete, messageCreate } from '../api/message/message'
import { findDepartmentAndID } from '../api/department/department'
import { findByDepartmentID } from '../api/user'
import { ChatDotRound, DeleteFilled, Delete, Message, Edit } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTabsStore } from '../store/store'
const useData = useTabsStore()

const state = reactive({
    activeTab: 'one',
    // 部门列表
    departmentList: [],
    userList: [],
    tabTitle: [
        { title: '全部消息', tabName: 'one' },
        { title: '未读消息', tabName: 'two' },
        { title: '已读消息', tabName: 'three' }
    ],
    editFormData: {
        operationType: 'announcement',
        userId: '',
        message: '',
        messagesContent: ''
    },
    selectedIds: [],
    messageList: [],
    page: {
        pageNum: 1,
        pageSize: 5,
        total: 30
    },
    rules: {
        departmentID: [
            { required: true, message: '请选择部门', trigger: 'blur' },
        ],
        userId: [
            { required: true, message: '请选择部门账号', trigger: 'blur' },
        ],
        message: [
            { required: true, message: '请输入公告标题', trigger: 'blur' },
        ]
    },
    messageStatus: '',
    messageDialogVisible: false
})
const init = async () =>
{
    const result = await messageRead({ messageStatus: state.messageStatus, pageNum: state.page.pageNum, pageSize: state.page.pageSize, operationType: 'message', })
    if (result.meta.status === 200) {
        state.messageList = result.data.readResult
        console.log(state.messageList, "消息列表");
        // || item.user_id === useData.getUserData().UserID
        for (let index = 0; index < state.messageList.length; index++) {
            state.messageList[index].operation_date = formatDate(state.messageList[index].operation_date)
        }
        state.page.total = result.data.total
        state.page.pageSize = result.data.pageSize
        state.page.pageNum = result.data.pageNum
    }
}
// 分页
const handlehSizeChange = (val) =>
{
    state.page.pageSize = val;
    state.page.pageNum = 1;
    init()
}
const handlehCurrentChange = (val) =>
{
    state.page.pageNum = Math.ceil(val);
    init()
}
const handleTabClick = (tab, event) =>
{

    if (tab.index == 0) {
        state.messageStatus = ''
        init()
    } else if (tab.index == 1) {
        state.messageStatus = 1
        init()
    } else if (tab.index == 2) {
        state.messageStatus = 2
        init()
    }
}
// 选择
const handleSelectionChange = (selection) =>
{
    state.selectedIds = selection.map(item => item.id);
    console.log("选择的id", state.selectedIds);
}
const deleteAll = () =>
{
    if (state.selectedIds.length === 0) {
        // 如果没有选择序号，显示提示
        ElMessage({
            showClose: true,
            message: '请选择序号',
            type: 'warning',
        })
    } else {
        // 弹出确认删除的对话框
        ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(async () =>
            {
                // 用户点击确定，执行删除操作
                let deleteStatus = true;

                for (const item of state.selectedIds) {
                    const res = await messageDelete({ messageID: item });
                    console.log(res);

                    // 如果删除操作失败
                    if (res.meta.status !== 200) {
                        deleteStatus = false;
                        break;  // 停止循环，不再继续删除剩余的项
                    }
                }

                // 根据删除操作的状态值显示相应的提示
                if (deleteStatus) {
                    ElMessage({
                        showClose: true,
                        message: '删除成功',
                        type: 'success',
                    });
                } else {
                    ElMessage({
                        showClose: true,
                        message: '删除失败',
                        type: 'error',
                    });
                }

                // 删除完成后执行初始化或其他操作
                init();
            })
            .catch(() =>
            {
                ElMessage('已取消')
                // 用户点击取消，不执行任何操作
            });
    }
};
const readAll = () =>
{
    if (state.selectedIds.length === 0) {
        // 如果没有选择序号，显示提示
        ElMessage({
            showClose: true,
            message: '请选择序号',
            type: 'warning',
        })
    } else {
        // 弹出确认删除的对话框
        ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(async () =>
            {
                // 用户点击确定，执行删除操作
                let deleteStatus = true;

                for (const item of state.selectedIds) {
                    const res = await messageUpdate({ messageID: item });
                    console.log(res);

                    // 如果删除操作失败
                    if (res.meta.status !== 200) {
                        deleteStatus = false;
                        break;  // 停止循环，不再继续删除剩余的项
                    }
                }

                // 根据删除操作的状态值显示相应的提示
                if (deleteStatus) {
                    ElMessage({
                        showClose: true,
                        message: '操作成功',
                        type: 'success',
                    });
                } else {
                    ElMessage({
                        showClose: true,
                        message: '删除失败',
                        type: 'error',
                    });
                }

                // 删除完成后执行初始化或其他操作
                init();
            })
            .catch(() =>
            {
                ElMessage('已取消')
                // 用户点击取消，不执行任何操作
            });
    }
}
const editFormRef = ref()
const editMessage = () =>
{
    editFormRef.value.validate(valid =>
    {
        if (valid) {
            ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () =>
            {
                const result = await messageCreate(state.editFormData)
                if (result.meta.status !== 200) {
                    ElMessage({
                        showClose: true,
                        message: '发送失败',
                        type: 'error',
                    })
                }
                ElMessage({
                    showClose: true,
                    message: '发送成功',
                    type: 'success',
                })
                state.messageDialogVisible = false
            }).catch(() =>
            {
                ElMessage('已取消')
            })
        }
    })
}
// 获取部门全部名称
const getAllDepartmentNames = async () =>
{
    const { departmentAndID } = await findDepartmentAndID()
    state.departmentList = departmentAndID
}
// 根据部门ID获取部门账号
const getAccount = async (departmentID) =>
{
    const result = await findByDepartmentID({ departmentID: departmentID })
    state.userList = result.data
    console.log("=======+++++++++>", result);
}
// 获取部门ID
const selectDepartmentID = () =>
{
    const id = state.editFormData.departmentID
    getAccount(id)
}
// 获取输入的内容
const EditContent = (data) =>
{
    state.editFormData.messagesContent = data
}
onMounted(() =>
{
    init()
    getAllDepartmentNames()
})
</script>

<style lang="scss" scoped></style>